package coder

import "sync"

const (
	ChannelSize = 4 * 8
)

// Channel 通道选择
type Channel struct {
	channels []bool
	sync.Once
}

// Enable 选择指定通道, 通道号从1开始,最大32(4字节) 只可选择不可取消. 如需取消,需要重新创建Channel对象
func (ch *Channel) Enable(n int) {
	if n <= 0 || n > ChannelSize {
		return
	}
	ch.Do(func() {
		ch.channels = make([]bool, ChannelSize)
	})
	ch.channels[n-1] = true
}

func (ch *Channel) build() (r []byte) {
	r = make([]byte, ChannelSize/8)
	if len(ch.channels) == 0 { // 没有打开的通道
		return
	}
	for i := range r {
		for j := 0; j < (i+1)*8; j++ {
			r[i] <<= 1
			if ch.channels[ChannelSize-1-j] {
				r[i] ^= 1
			}
		}
	}

	return
}
